package com.soFun.controller;

import com.soFun.service.RagService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 知识库控制器，提供知识库相关API端点
 */
@RestController
@RequestMapping("/kb")
@RequiredArgsConstructor
public class KnowledgeBaseController {

    private final RagService ragService;

    /**
     * 创建知识库
     * @param requestBody 包含知识库名称的请求体
     * @return 包含知识库ID的响应
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createKnowledgeBase(@RequestBody Map<String, String> requestBody) {
        String name = requestBody.get("name");
        if (name == null || name.trim().isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("status", "error");
            error.put("message", "知识库名称不能为空");
            return ResponseEntity.badRequest().body(error);
        }
        
        String knowledgeBaseId = ragService.createKnowledgeBase(name);
        
        Map<String, Object> response = new HashMap<>();
        response.put("status", "success");
        response.put("knowledgeBaseId", knowledgeBaseId);
        response.put("name", name);
        response.put("timestamp", System.currentTimeMillis());
        
        return ResponseEntity.status(HttpStatus.CREATED).body(response);
    }
    
    /**
     * 添加文本到知识库
     * @param knowledgeBaseId 知识库ID
     * @param requestBody 包含文本内容和元数据的请求体
     * @return 操作结果
     */
    @PostMapping("/{knowledgeBaseId}/text")
    public ResponseEntity<Map<String, Object>> addTextToKnowledgeBase(
            @PathVariable String knowledgeBaseId,
            @RequestBody Map<String, Object> requestBody) {
        
        String text = (String) requestBody.get("text");
        if (text == null || text.trim().isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("status", "error");
            error.put("message", "文本内容不能为空");
            return ResponseEntity.badRequest().body(error);
        }
        
        @SuppressWarnings("unchecked")
        Map<String, String> metadata = (Map<String, String>) requestBody.getOrDefault("metadata", new HashMap<>());
        
        try {
            ragService.addTextToKnowledgeBase(knowledgeBaseId, text, metadata);
            
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("message", "文本已添加到知识库");
            response.put("knowledgeBaseId", knowledgeBaseId);
            
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            Map<String, Object> error = new HashMap<>();
            error.put("status", "error");
            error.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
        }
    }
    
    /**
     * 从文件添加内容到知识库
     * @param knowledgeBaseId 知识库ID
     * @param requestBody 包含文件路径的请求体
     * @return 操作结果
     */
    @PostMapping("/{knowledgeBaseId}/file")
    public ResponseEntity<Map<String, Object>> addFileToKnowledgeBase(
            @PathVariable String knowledgeBaseId,
            @RequestBody Map<String, String> requestBody) {
        
        String filePath = requestBody.get("filePath");
        if (filePath == null || filePath.trim().isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("status", "error");
            error.put("message", "文件路径不能为空");
            return ResponseEntity.badRequest().body(error);
        }
        
        try {
            ragService.addFileToKnowledgeBase(knowledgeBaseId, filePath);
            
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("message", "文件内容已添加到知识库");
            response.put("knowledgeBaseId", knowledgeBaseId);
            
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            Map<String, Object> error = new HashMap<>();
            error.put("status", "error");
            error.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
        } catch (IOException e) {
            Map<String, Object> error = new HashMap<>();
            error.put("status", "error");
            error.put("message", "文件读取失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }
    
    /**
     * 查询知识库
     * @param knowledgeBaseId 知识库ID
     * @param requestBody 包含问题的请求体
     * @return 包含回答的响应
     */
    @PostMapping("/{knowledgeBaseId}/query")
    public ResponseEntity<Map<String, Object>> queryKnowledgeBase(
            @PathVariable String knowledgeBaseId,
            @RequestBody Map<String, String> requestBody) {
        
        String question = requestBody.get("question");
        if (question == null || question.trim().isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("status", "error");
            error.put("message", "问题不能为空");
            return ResponseEntity.badRequest().body(error);
        }
        
        try {
            String answer = ragService.queryKnowledgeBase(knowledgeBaseId, question);
            
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("question", question);
            response.put("answer", answer);
            response.put("knowledgeBaseId", knowledgeBaseId);
            
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            Map<String, Object> error = new HashMap<>();
            error.put("status", "error");
            error.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
        }
    }
    
    /**
     * 获取知识库信息
     * @param knowledgeBaseId 知识库ID
     * @return 包含知识库信息的响应
     */
    @GetMapping("/{knowledgeBaseId}")
    public ResponseEntity<Map<String, Object>> getKnowledgeBaseInfo(@PathVariable String knowledgeBaseId) {
        try {
            Map<String, Object> info = ragService.getKnowledgeBaseInfo(knowledgeBaseId);
            info.put("status", "success");
            
            return ResponseEntity.ok(info);
        } catch (IllegalArgumentException e) {
            Map<String, Object> error = new HashMap<>();
            error.put("status", "error");
            error.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
        }
    }
} 